package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachplanService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**课程计划业务实现类
 * @author 18447
 * @date 2024/08/15
 */
@Service
public class TeachplanServiceImpl implements TeachplanService {

    @Autowired
    TeachplanMapper teachplanMapper;

    @Autowired
    TeachplanMediaMapper teachplanMediaMapper;

    /**根据id查询课程计划
     * @param courseId
     * @return {@link List}<{@link TeachplanDto}>
     */
    @Override
    public List<TeachplanDto> findTeachplanTree(long courseId) {
        return teachplanMapper.selectTreeNodes(courseId);
    }

    /**保存课程计划
     * @param teachplanDto
     */
    @Transactional
    @Override
    public void saveTeachplan(SaveTeachplanDto teachplanDto) {
        //课程计划id
        Long id = teachplanDto.getId();
        //修改课程计划
        if(id!=null){
            Teachplan teachplan = teachplanMapper.selectById(id);
            BeanUtils.copyProperties(teachplanDto,teachplan);
            teachplanMapper.updateById(teachplan);
        }else{
            //取出同父同级别的课程计划数量
            int count = getTeachplanCount(teachplanDto.getCourseId(), teachplanDto.getParentid());
            Teachplan teachplanNew = new Teachplan();
            //设置排序号
            teachplanNew.setOrderby(count+1);
            BeanUtils.copyProperties(teachplanDto,teachplanNew);
            teachplanMapper.insert(teachplanNew);
        }

    }

    /**
     * @description 获取最新的排序号
     * @param courseId  课程id
     * @param parentId  父课程计划id
     * @return int 最新排序号
     * @author Mr.M
     * @date 2022/9/9 13:43
     */
    private int getTeachplanCount(long courseId,long parentId){
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId,courseId);
        queryWrapper.eq(Teachplan::getParentid,parentId);
        Integer count = teachplanMapper.selectCount(queryWrapper);
        return count;
    }

    @Transactional
    @Override
    public void deleTeachplan(Long id) {
        //判断当前节点是否为父节点
        Teachplan teachplan = teachplanMapper.selectById(id);
        Long parentid = teachplan.getParentid();
        //如果是父节点的话就判断是否下面有子节点
        if(parentid==0){
            //判断当前课程计划id是否是其他节点的父节点
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getParentid,id);
            Integer count = teachplanMapper.selectCount(queryWrapper);
            //当前父节点
            if(count>0){
                throw new XueChengPlusException("课程计划信息还有子级信息，无法操作");
            }else{
                //如果没有子节点直接删除
                int result_i = teachplanMapper.deleteById(id);
                if(result_i<=0){
                    throw new XueChengPlusException("删除第一级别章节失败");
                }
            }
        }else{
            //如果不为父节点，为第二级别小章节
            int result_i1 = teachplanMapper.deleteById(id);
            if(result_i1<=0){
                throw new XueChengPlusException("删除第二级别小章节失败");
            }
            //同时删除teachplan_media对应记录
            LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TeachplanMedia::getTeachplanId,id);
            int count = teachplanMediaMapper.selectCount(queryWrapper);
            //media中有视频则删除
            if(count>0){
                int result_i3  = teachplanMediaMapper.delete(queryWrapper);
                if(result_i3<=0){
                    throw new XueChengPlusException("删除第二级别小章节关联的视频记录失败");
                }
            }
        }
    }

    @Transactional
    @Override
    public void moveDownTeachplan(Long id) {
        Teachplan teachplan = teachplanMapper.selectById(id);
        Long courseId = teachplan.getCourseId();
        //先根据course_id查询出当前的分组
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId,courseId);
        List<TeachplanDto> teachplanDto = teachplanMapper.selectTreeNodes(courseId);
        Long parentid = teachplan.getParentid();
        //如果是父节点，先判断当前元素是否在最底端，若是最底端提示无法下移，若不是则根下级交换位置连同子集也一起交换
        if(parentid == 0){
            //设置index初始值
            int index = 0;
            //节点list的长度
            int size = teachplanDto.size();
            //遍历查找当前节点位置
            for(int i=0;i<size;i++){
                Long blId = teachplanDto.get(i).getId();
                if(blId.equals(id)){
                    index = i;
                    break;
                }
            }
            if(index == size){
                XueChengPlusException.cast("当前节点已是最后一位无法下移");
            }
            Long nowId = teachplanDto.get(index).getId();
            Long nextId = teachplanDto.get(index + 1).getId();

            Integer orderby = teachplanDto.get(index).getOrderby();
            Integer nextOrderby = teachplanDto.get(index + 1).getOrderby();
            //当前id的先换成临时的order
            teachplanMapper.updateOrderby(nextOrderby,nowId);
            //再将下一位的order换成当前的order
            teachplanMapper.updateNextOrderby(orderby,nextId);

        }else{
            //若不是父节点，先判断当前元素是否在最底端，若是最底端提示无法下移，否则直接和下一位子集交换位置，并将更新后的id同步到media表
            //遍历查找当前id的父节点
            int index = 0;
            int size = teachplanDto.size();
            //遍历查找当前节点位置
            for(int i=0;i<size;i++){
                Long blId = teachplanDto.get(i).getId();
                if(blId.equals(parentid)){
                    index = i;
                    break;
                }
            }
            //获取当前父节点的子集
            List<TeachplanDto> teachPlanTreeNodes = teachplanDto.get(index).getTeachPlanTreeNodes();
            //遍历子集获得当前id的位置
            int childSize = teachPlanTreeNodes.size();
            //遍历子集
            for(int i=0;i<childSize;i++){
                Long blId = teachPlanTreeNodes.get(i).getId();
                if(blId.equals(id)){
                    index = i;
                    break;
                }
            }
            if(index == childSize){
                XueChengPlusException.cast("当前节点已是最后一位无法下移");
            }
            Long nowId = teachPlanTreeNodes.get(index).getId();
            Long nextId = teachPlanTreeNodes.get(index + 1).getId();

            Integer orderby = teachPlanTreeNodes.get(index).getOrderby();
            Integer nextOrderby = teachPlanTreeNodes.get(index + 1).getOrderby();
            //当前id的先换成临时的order
            teachplanMapper.updateOrderby(nextOrderby,nowId);
            //再将下一位的order换成当前的order
            teachplanMapper.updateNextOrderby(orderby,nextId);
        }
    }

    @Transactional
    @Override
    public void moveUpTeachplan(Long id) {
        Teachplan teachplan = teachplanMapper.selectById(id);
        Long courseId = teachplan.getCourseId();
        //先根据course_id查询出当前的分组
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId,courseId);
        List<TeachplanDto> teachplanDto = teachplanMapper.selectTreeNodes(courseId);
        Long parentid = teachplan.getParentid();
        //如果是父节点，先判断当前元素是否在最底端，若是最底端提示无法下移，若不是则根下级交换位置连同子集也一起交换
        if(parentid == 0){
            //设置index初始值
            int index = 0;
            //节点list的长度
            int size = teachplanDto.size();
            //遍历查找当前节点位置
            for(int i=0;i<size;i++){
                Long blId = teachplanDto.get(i).getId();
                if(blId.equals(id)){
                    index = i;
                    break;
                }
            }
            if(index == 0){
                XueChengPlusException.cast("当前节点已是第一位无法上移");
            }
            Long nowId = teachplanDto.get(index).getId();
            Long nextId = teachplanDto.get(index - 1).getId();

            Integer orderby = teachplanDto.get(index).getOrderby();
            Integer nextOrderby = teachplanDto.get(index - 1).getOrderby();
            //当前id的先换成临时的order
            teachplanMapper.updateOrderby(nextOrderby,nowId);
            //再将下一位的order换成当前的order
            teachplanMapper.updateNextOrderby(orderby,nextId);
        }else{
            //若不是父节点，先判断当前元素是否在最底端，若是最底端提示无法下移，否则直接和下一位子集交换位置，并将更新后的id同步到media表
            //遍历查找当前id的父节点
            int index = 0;
            int size = teachplanDto.size();
            //遍历查找当前节点位置
            for(int i=0;i<size;i++){
                Long blId = teachplanDto.get(i).getId();
                if(blId.equals(parentid)){
                    index = i;
                    break;
                }
            }
            //获取当前父节点的子集
            List<TeachplanDto> teachPlanTreeNodes = teachplanDto.get(index).getTeachPlanTreeNodes();

            //遍历子集获得当前id的位置
            int childSize = teachPlanTreeNodes.size();
            for(int i=0;i<childSize;i++){
                Long blId = teachPlanTreeNodes.get(i).getId();
                if(blId.equals(id)){
                    index = i;
                    break;
                }
            }
            if(index == 0){
                XueChengPlusException.cast("当前节点已是第一位无法上移");
            }

            Long nowId = teachPlanTreeNodes.get(index).getId();
            Long nextId = teachPlanTreeNodes.get(index - 1).getId();

            Integer orderby = teachPlanTreeNodes.get(index).getOrderby();
            Integer nextOrderby = teachPlanTreeNodes.get(index - 1).getOrderby();
            //当前id的先换成临时的order
            teachplanMapper.updateOrderby(nextOrderby,nowId);
            //再将下一位的order换成当前的order
            teachplanMapper.updateNextOrderby(orderby,nextId);
        }
    }
}
